//
//  FamilyAddViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/24.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class FamilyAddViewController: BaseViewController {
    
    private var viewModel = FamilyAddViewModel(model: FamilyAddModel()) {
        didSet {
            tableView.isHidden = false
            tableView.reloadData()
        }
    }
    
    var updateClosure: (() -> Void)?
    
    private let patientId: String
    private let addType: FamilyAddType
    
    init(patientId: String = "", addType: FamilyAddType) {
        self.patientId = patientId
        self.addType = addType
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !patientId.isEmpty, addType == .edit { loadData() }
    }
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = addType == .edit
            tableView.tableFooterView = footerView
            tableView.register(FamilyAddFormCell.nibForCell(),
                               forCellReuseIdentifier: FamilyAddFormCell.reuseIdentifier())
            
//            let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
//            tap.cancelsTouchesInView = false
//            tableView.addGestureRecognizer(tap)
        }
    }
    
    lazy var footerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.frame = CGRect(x: 0, y: 0, width: screenW, height: 30)
        return view
    }()
}

extension FamilyAddViewController {
    private func loadData() {
        activityView.startAnimating()
        FamilyAddViewModel.getFamilyMemberDetail(patientId: patientId, success: { model in
            self.activityView.stopAnimating()
            self.viewModel = FamilyAddViewModel(model: model)
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    private func deletFamily() {
        HUDTool.showActivity()
        FamilyAddViewModel.deleteFamily(familyId: viewModel.id) { (msg, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: msg)
            case .success:
                HUDTool.show(message: "删除成功")
                self.updateClosure?()
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
//    @objc private func dismissKeyboard() {
//        tableView.endEditing(true)
//    }
}

extension FamilyAddViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: FamilyAddFormCell.reuseIdentifier(), for: indexPath) as! FamilyAddFormCell
        let cell = FamilyAddFormCell.nibForCell().instantiate(withOwner: nil, options: nil)[0] as! FamilyAddFormCell
        
        
        cell.delegate = self
        let cellType = FamilyAddFormCellType(rawValue: indexPath.row) ?? .name
        cell.configure(with: viewModel, cellType: cellType, addType: addType)
        return cell
    }
}

extension FamilyAddViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellType = FamilyAddFormCellType(rawValue: indexPath.row) ?? .name
        switch cellType {
        case .sure: return 110
        default: return 60
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let cellType = FamilyAddFormCellType(rawValue: indexPath.row) ?? .name
        
        switch cellType {
        case .area:
            let addressVc = AddressViewController()
            addressVc.modalPresentationStyle = .custom
            addressVc.chooseClosure = { [weak self] model in
                guard let self = self else { return }
                self.viewModel.area = "\(model.provinceName) \(model.cityName) \(model.areaName)"
                self.viewModel.provinceId = model.provinceId
                self.viewModel.cityId = model.cityId
                self.viewModel.regionId = model.areaId
                self.tableView.reloadData()
            }
            present(addressVc, animated: true) {
                addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
            }
        case .relation:
            let picker = UINib.loadViewFrom(CommonPickerView.self)
            picker.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
            picker.show(type: .relation)
            picker.selectedClosure = { [weak self] model in
                guard let self = self else { return }
                self.viewModel.relation = model.code
                self.viewModel.relationName = model.name
                self.tableView.reloadData()
            }
        default: break
        }
    }
}

extension FamilyAddViewController: FamilyAddFormCellDelegate {
    func familyFormCell(_ cell: FamilyAddFormCell, didEndEditing vm: FamilyAddViewModel) {
        viewModel = vm
    }
    
    func familyFormCell(_ cell: FamilyAddFormCell, didClickedCommonly vm: FamilyAddViewModel) {
        viewModel = vm
    }
    
    func familyFormCell(didClickedSure cell: FamilyAddFormCell) {
        if addType == .edit {
            createAlert()
            return
        }
        if !viewModel.isName {
            HUDTool.show(message: viewModel.nameMsg)
            return
        }
        
        if !viewModel.isIdCard {
            HUDTool.show(message: viewModel.idCardMsg)
            return
        }
        
        if !viewModel.isPhone {
            HUDTool.show(message: viewModel.phoneMsg)
            return
        }
        
        let paras: [String: Any] = [
            "name": viewModel.name,
            "idcard": viewModel.idcard,
            "phone": viewModel.phone,
            "province": viewModel.provinceId,
            "city": viewModel.cityId,
            "region": viewModel.regionId,
            "relation": viewModel.relation,
            "addr": viewModel.addr,
            "isDefault": viewModel.isDefault,
            "isDelete": 1
        ]
        HUDTool.showActivity()
        FamilyAddViewModel.addOrEditFamily(paras: paras) { (errorMsg, code) in
            HUDTool.hideActivity()
            switch code {
            case .success:
                HUDTool.show(message: "添加成功")
                self.updateClosure?()
                self.navigationController?.popViewController(animated: true)
            case .failure:
                HUDTool.showError(message: errorMsg)
            }
        }
    }
}

extension FamilyAddViewController {
    func createAlert() {
        let alert = UIAlertController(title: "确定要删除该家庭成员吗？", message: "", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "确定", style: .destructive) { (action) in
            self.deletFamily()
        }
        let cancelAction = UIAlertAction(title: "关闭", style: .default) { (action) in
            
        }
        alert.addAction(cancelAction)
        alert.addAction(confirmAction)
        self.present(alert, animated: true) {
            
        }
    }
}
